//
//  GRConfirmOrderViewController.m
//  YC_GRice
//
//  Created by luojinrong11 on 2018/7/8.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRConfirmOrderViewController.h"
#import "GRGoodTableViewCell.h"
#import "GRPayBillView.h"
#import "GRAddressListViewController.h"
#import "GRConfirmOrderAction.h"
#import "GRConfirmSectionHeaderView.h"

@interface GRConfirmOrderViewController ()<UITableViewDataSource,UITableViewDelegate,GRPayBillViewDelegate,GRAddressListViewControllerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *goodList;
@property (strong, nonatomic) IBOutlet UIView *headerView;
@property (strong, nonatomic) IBOutlet UIView *footView;
@property(nonatomic,strong)NSMutableArray * goodArr;
@property(nonatomic,strong)GRConfirmOrderAction *confirmOrderAction;
@property(nonatomic,strong)GRConfrimOrderModel * confirmOrderModel;
@property (weak, nonatomic) IBOutlet UIView *addressView;

@property (weak, nonatomic) IBOutlet UILabel *priceAndCountLabel;
@property (weak, nonatomic) IBOutlet UIButton *createAddBt;

@property (weak, nonatomic) IBOutlet UILabel *namePhoneLabel;

@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@property (weak, nonatomic) IBOutlet UIImageView *defaultAddrImageView;
@property (nonatomic,strong)GRInvoiceModel * invoiceModel;

@property (weak, nonatomic) IBOutlet UILabel *actualPriceLabel;

@property (weak, nonatomic) IBOutlet UILabel *invoiceTextLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *footTopOffset;

@property (weak, nonatomic) IBOutlet UILabel *stageLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *priceTop;
@property (weak, nonatomic) IBOutlet UIView *stageView;

@end

@implementation GRConfirmOrderViewController
-(NSMutableArray *)goodArr {
    if (!_goodArr) {
        _goodArr = [NSMutableArray array];
    }
    return _goodArr;
}

-(GRConfirmOrderAction *)confirmOrderAction{
    if (!_confirmOrderAction) {
        _confirmOrderAction = [[GRConfirmOrderAction alloc]init];
    }
    return _confirmOrderAction;
}

-(GRInvoiceModel *)invoiceModel{
    if (!_invoiceModel) {
        _invoiceModel = [[GRInvoiceModel alloc]init];
    }
    return _invoiceModel;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barTintColor = KGMTHEM_COLOR;
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"确认订单";
    [self.goodList registerNib:[UINib nibWithNibName:@"GRGoodTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"goodCell"];
    self.goodList.tableFooterView = self.footView;
    self.goodList.tableHeaderView = self.headerView;
    [self.createAddBt.layer setBorderWidth:1];
    [self.createAddBt.layer setBorderColor:[HEXCOLOR(0x000000) CGColor]];
    [self loadData];
  
}

-(void)loadData{
    NSDictionary * dic;
    if (_isCar) {
        if (_ischangeRate) {
            dic = @{@"cart":@(YES),@"sourcePlatform":@"ios",@"firstRate":@(self.rate),@"totalStages":@(self.stage)};
        }else{
             dic = @{@"cart":@(YES),@"sourcePlatform":@"ios"};
        }
       
    }else{
        if (_ischangeRate) {
            dic = @{
                    @"cart":@(NO),
                    @"goodsId":self.goodId,
                    @"quantity":self.quantity,
                    @"sourcePlatform":@"ios",
                    @"specId":@(self.specId),
                    @"firstRate":@(self.rate),
                    @"totalStages":@(self.stage)
                    };
        }else{
            dic = @{
                    @"cart":@(NO),
                    @"goodsId":self.goodId,
                    @"quantity":self.quantity,
                    @"sourcePlatform":@"ios",
                    @"specId":@(self.specId)
                    };
        }
    }
    WEAKSELF
    [self.confirmOrderAction  getConfirmOrderFirstInfo:dic SuccessBlock:^(GRConfrimOrderModel *orderInfoModel) {
        weakSelf.confirmOrderModel = orderInfoModel;
        [self updateUI];
    } ];
}

-(void)updateUI{
    if (self.confirmOrderModel.defAddressModel) {
         [self selectedAddressModel:self.confirmOrderModel.defAddressModel];
    }
    if (self.rate == 100) {
        self.stageView.hidden = YES;
        self.priceTop.constant = 14.5;
    }else{
        self.priceTop.constant = 6;
        self.stageView.hidden = NO;
        CGFloat monthPrice = ([self.confirmOrderModel.totalPrice floatValue]*(100 -self.rate)*0.01)/self.stage;
        self.stageLabel.text = [NSString stringWithFormat:@"￥%.2lf x%ld期",monthPrice,self.stage];
    }
    
    if (self.confirmOrderModel.isInvoice) {
        self.confirmOrderModel.isInvoice = YES;
        self.invoiceTextLabel.text = @"电子发票-个人";
        self.footTopOffset.constant = 60;
    }else{
        self.invoiceTextLabel.text = @"暂不支持";
        self.footTopOffset.constant = 0;
    }
    self.actualPriceLabel.text = [NSString stringWithFormat:@"￥%.2lf",[self.confirmOrderModel.totalPrice floatValue]] ;
    NSString  *string = [NSString stringWithFormat:@"共%ld件商品 ￥%.2lf 优惠0.00",self.confirmOrderModel.totalQuantity,[self.confirmOrderModel.totalPrice floatValue]];

    NSRange rangeF =  [string rangeOfString:@"优惠" ];
    NSRange rangeS = [ string rangeOfString:@"￥" ];
    
    NSMutableAttributedString * countAtrbutingString = [[NSMutableAttributedString alloc]initWithString:string];
    [countAtrbutingString addAttributes:@{
                                          NSFontAttributeName:[UIFont systemFontOfSize:23],
                                          NSForegroundColorAttributeName:HEXCOLOR(0xF11544)
                                          } range:NSMakeRange(rangeS.location+rangeS.length, rangeF.location - rangeS.location-1)];
    [countAtrbutingString addAttributes:@{
                                          NSFontAttributeName:[UIFont systemFontOfSize:15],
                                          NSForegroundColorAttributeName:HEXCOLOR(0xF11544)
                                          } range:rangeS];
    
    self.priceAndCountLabel.attributedText = countAtrbutingString;
    [self.goodList reloadData];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GRGoodTableViewCell * goodCell = [tableView dequeueReusableCellWithIdentifier:@"goodCell" forIndexPath:indexPath];
    GRConfirmOderGoodInfo * goodInfoModel = self.confirmOrderModel.orders[indexPath.section];
    goodCell.orderGoodModel = goodInfoModel.orderInfos[indexPath.row] ;
    
    return goodCell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    GRConfirmSectionHeaderView * sectionHeaderView = [GRConfirmSectionHeaderView xx_instantiateFromNib];
    GRConfirmOderGoodInfo * goodInfoModel = self.confirmOrderModel.orders[section];
    sectionHeaderView.vendorNameLabel.text = goodInfoModel.vendorName;
    if (section == 0) {
        sectionHeaderView.bkView.hidden = NO;
    }else{
        sectionHeaderView.bkView.hidden = YES;
    }
    return sectionHeaderView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 110;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KscreenWidth, 10)];
    footView.backgroundColor = [UIColor clearColor];
    return footView;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    GRConfirmOderGoodInfo * goodInfoModel = self.confirmOrderModel.orders[section];
    return goodInfoModel.orderInfos.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.confirmOrderModel.orders.count;
}

- (IBAction)nextAction:(id)sender {
    if (!self.confirmOrderModel.defAddressModel.addr) {
        NSLog(@"请选择地址");
        [GRHUD showMessage:@"请选择收货地址"];
        return;
    }
    NSDictionary * orderDic = @{
                            @"addressId":@(self.confirmOrderModel.defAddressModel.id),
                            @"invoice":@(self.invoiceModel.invoice),
                            @"invoiceFlg":@(self.invoiceModel.invoiceFlg),
                            @"invoiceMobile":self.invoiceModel.invoiceMobile?self.invoiceModel.invoiceMobile:@"",
                            @"invoiceName":self.invoiceModel.invoiceName?self.invoiceModel.invoiceName:@"",
                            @"invoiceTyp":@(self.invoiceModel.invoiceType),
                            @"memo":@"",
                            @"orderId":[self.confirmOrderModel.orderIdArr componentsJoinedByString:@","],
                            @"personSn":self.invoiceModel.personSn?self.invoiceModel.personSn:@"",
                            @"selectId":@(self.confirmOrderModel.selectId)
                                };
//    GRPayDetailViewController *payDetailVC =
//    [[GRPayDetailViewController alloc]init];
//    payDetailVC.orderDic = orderDic;
//    [self.navigationController pushViewController:payDetailVC animated:YES];
}

- (IBAction)billTypeAction:(id)sender {
    if (self.confirmOrderModel.isInvoice) {
        [GRPayBillView ShowInView:[UIApplication sharedApplication].keyWindow Delegate:self];
    }

}


-(void)customerNeedInvoiceType:(GRInvoiceModel *)invoiceModel{
    self.invoiceModel = invoiceModel ;
    if (invoiceModel.invoice) {
        self.invoiceTextLabel.text = [NSString stringWithFormat:@"%@-%@" ,(invoiceModel.invoiceFlg ==0?@"电子发票":@"纸质发票"), (invoiceModel.invoiceType == 0 ?@"个人":@"公司")];
    }
}

- (IBAction)createNewAddAction:(id)sender {
    [self pushAddressVC];
}

- (IBAction)selecteAddressAction:(id)sender {
    [self pushAddressVC];
   
}

-(void)pushAddressVC{
    GRAddressListViewController * addressListVC = [[GRAddressListViewController alloc]init];
    addressListVC.delegate = self;
    addressListVC.isSelected = YES;
    [self.navigationController pushViewController:addressListVC animated:YES];
    
}

#pragma mark - GRAddressListViewControllerDelegate
-(void)selectedAddressModel:(GRMyAddressEditorModel *)addressModel{
    self.confirmOrderModel.defAddressModel = addressModel;
    self.addressView.hidden = NO;
    self.createAddBt.hidden = YES;
    self.defaultAddrImageView.hidden = !addressModel.isDefault;
    self.namePhoneLabel.text = [NSString stringWithFormat:@"%@  %@",addressModel.consigneeName,addressModel.consigneeMobile];
    self.addressLabel.text = [NSString stringWithFormat:@"%@%@%@%@",addressModel.province,addressModel.city,addressModel.area,addressModel.addr];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
